<template>
  <div>
    <page-header title="库存管理"> </page-header>
    <div class="mt-[16px]">
      <n-grid x-gap="12" :cols="24">
        <n-gi :span="5">
          <n-input
            v-model:value="paginationResult.keyword"
            clearable
            placeholder="请输入产品名称"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi :span="5">
          <n-select
            value-field="id"
            label-field="name"
            clearable
            v-model:value="paginationResult.branchId"
            :options="userStore.ownBranches"
            placeholder="请选择店铺"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi :span="5">
          <n-select
            v-model:value="paginationResult.brandId"
            clearable
            placeholder="请选择品牌"
            value-field="id"
            label-field="name"
            :options="brandsList"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi :span="5">
          <n-select
            v-model:value="paginationResult.categoryId"
            clearable
            placeholder="请选择产品类别"
            value-field="id"
            label-field="name"
            :options="categoriesList"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi :span="4" class="flex items-center">
          <n-checkbox
            v-model:checked="paginationResult.inStock"
            :checked-value="'1'"
            :unchecked-value="'0'"
            @update:checked="handleSearch"
          >
            只看有库存
          </n-checkbox>
        </n-gi>
      </n-grid>
      <div class="mt-[16px]"></div>
      <BasicTable
        :table-props="tableResult"
        :columns="columns"
        :pagination-props="paginationResult"
        maxHeight="66vh"
        minHeight="48vh"
        @changePage="handleChangePage"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { h, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { debounce, get } from "lodash-es";
import { Eye } from "@vicons/ionicons5";
import { NButton, NIcon, NTag } from "naive-ui";
import { useUserStore } from "@/store/modules/user.store";
import { useTableHook } from "@/components/normal/basicTable/useTableHook";
import { getInventoryList } from "@/api/inventory/inventory.api";
import { getBrands } from "@/api/product/brand.api";
import { getCategories } from "@/api/product/category.api";
import { currencyFormat } from "@/common/utils/currencyFormatter";
import * as RouterNames from "@/router/routerNames";
import { Category } from "@/types/model/product/vos/category.vo";

const columns = [
  {
    title: "#",
    type: "index",
    key: "key",
    width: "5%",
    render: (_: any, index: number) => {
      return `${index + 1}`;
    },
  },
  {
    title: "产品",
    width: "240",
    fixed: "left",
    render: (row: any) => {
      return [
        h("div", row.variantName),
        h(NTag, { type: "success", bordered: false, size: "small" }, row.sku),
      ];
    },
  },
  {
    title: "所在门店",
    key: "branchName",
  },
  {
    title: "可用库存",
    key: "qtyAvailable",
  },
  {
    title: "入库锁定",
    key: "qtyLocked",
  },
  {
    title: "出库锁定",
    key: "qtySalesLocked",
  },
  {
    title: "产品类别",
    key: "categoryName",
  },
  {
    title: "品牌",
    key: "brandName",
  },
  {
    title: "平均成本",
    key: "avgCost",
    render: (row: any) => {
      return currencyFormat(row.avgCost);
    },
  },
  {
    title: "最新成本",
    key: "lastCost",
    render: (row: any) => {
      return currencyFormat(row.lastCost);
    },
  },
  {
    title: "操作",
    key: "actions",
    align: "right",
    fixed: "right",
    render: (row: any) => {
      return h(
        NButton,
        {
          size: "small",
          type: "primary",
          secondary: true,
          strong: true,
          class: "mr-2",
          onClick: () => handleNavToDetail(row.id),
        },
        {
          icon: () =>
            h(NIcon, null, {
              default: () => h(Eye),
            }),
        }
      );
    },
  },
];

const router = useRouter();
const userStore = useUserStore();

const categoriesList = ref<Category[]>([]);
const brandsList = ref<any[]>([]);

const { tableResult, paginationResult, getDataList, handleChangePage } =
  useTableHook<any>({
    api: getInventoryList,
    queryForm: {
      keyword: "",
      categoryId: undefined,
      brandId: undefined,
      inStock: "",
    },
  });

const handleNavToDetail = (id: string) => {
  router.push({
    name: RouterNames.INVENOTRY_DETAIL_PAGE.NAME,
    params: { id },
  });
};

const getBrandsList = async () => {
  try {
    const result = await getBrands({
      page: 1,
      pageSize: 1000,
    });
    brandsList.value = get(result, "result.records") || [];
  } catch (err) {
    console.log(err);
  }
};

const getCategoriesList = async () => {
  try {
    const result = await getCategories({
      page: 1,
      pageSize: 1000,
    });
    categoriesList.value = get(result, "result.records") || [];
  } catch (err) {
    console.log(err);
  }
};

const handleSearch = debounce(async function () {
  paginationResult.page = 1;
  getDataList();
}, 200);

onMounted(() => {
  getDataList();
  getBrandsList();
  getCategoriesList();
});
</script>
